package esi.t2no1.web.meterdata;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import esi.t2no1.dao.contract.ContractDAO;
import esi.t2no1.dao.meterdata.MeterDataDAO;
import esi.t2no1.dao.meterdata.MeterDataDTO;

/**
 * Controller that handles meterdata related views
 * 
 * @author Taavi Pauskar
 *
 */
@Controller
@RequestMapping(value = "/meterdata")
public class MeterdataController {

	private MeterDataDAO meterDataDAO;
	private ContractDAO contractDAO;

	@RequestMapping(method = RequestMethod.GET)
	public String getList(Model model) {
		model.addAttribute("meterData", meterDataDAO.getAllMeterData());
		return "meterdata/list";

	}

	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public String getView(@PathVariable Long id, Model model) {
		MeterDataDTO meterData = meterDataDAO.getMeterDataById(id);
		if (meterData == null) {
			model.addAttribute("error", "contract.notFound");
			return "meterdata/view";
		}
		model.addAttribute("meterdata", meterData);
		return "meterdata/view";
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public ModelAndView submitMeterData() {

		ModelAndView model = new ModelAndView("meterdata/add", "meterdata",
				new MeterDataDTO());
		model.addObject("facilityIds", contractDAO.getFacilityIds());
		return model;
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String createMeterData(
			@ModelAttribute("meterdata") MeterDataDTO meterdata,
			BindingResult result) {
		Date date = new Date();
		meterdata.setReadTime(date);
		meterdata.setAreaId(contractDAO.getAreaId(meterdata.getFacilityId()));
		Long meterdataId = meterDataDAO.createMeterData(meterdata);
		return "redirect:/meterdata/" + meterdataId;
	}

	@Autowired
	public void setMeterDataDAO(MeterDataDAO meterDataDAO) {
		this.meterDataDAO = meterDataDAO;
	}

	@Autowired
	public void getContracDAO(ContractDAO contractDAO) {
		this.contractDAO = contractDAO;
	}

}
